package mh.demo.jdk.util.concurrent.locks;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 《Java并发编程艺术》书中的读写锁的示例
 */
public class ReentrantReadWriteLockDemo {

    public static void main(String[] args) {
        // 暂未测试
    }

    private static class Cache {
        static Map<String, Object> map = new HashMap<>();
        static ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
        static Lock rLock = rwLock.readLock();
        static Lock wLock = rwLock.writeLock();

        public static Object get(String key) {
            rLock.lock();
            try {
                return map.get(key);
            } finally {
                rLock.unlock();
            }
        }

        public static Object put(String key, Object value) {
            wLock.lock();
            try {
                return map.put(key, value);
            } finally {
                wLock.unlock();
            }
        }

        public static void clear() {
            wLock.lock();
            try {
                map.clear();
            } finally {
                wLock.unlock();
            }
        }
    }
}
